import React, { useContext, useRef, useState } from 'react';
import { AutoComplete, Flex } from 'antd';
import { FieldProps } from '@rjsf/utils';
import { DownOutlined } from '@ant-design/icons';
import styles from './style.module.scss';
import { MessageContext } from '../CollapseTemplate';
export const AutoCompleteField = ({
  schema,
  onChange,
  formData,
  uiSchema,
  disabled,
}: FieldProps<string>) => {
  const { layout: layout1 } = useContext(MessageContext);
  const disabledBoolean = disabled
    ? disabled
    : (uiSchema['ui:disabled'] ?? false);
  const options = ((uiSchema['ui:options']?.options as Array<any>) ?? []).map(
    (item) => ({
      ...item,
      label: item?.title || item?.const || '',
      value: item.const || '',
    }),
  );

  const [placeholder, setPlaceholder] = useState('');
  const [valueInput, setValue] = useState(
    options.find((it) => it.value === formData)?.label,
  );
  const layout = uiSchema['ui:layout'] ?? layout1 ?? [1, 1];
  const [open, setOpen] = useState(false);
  const [isOPen, setIsOPen] = useState(false);
  const AutoCompleteRef = useRef(null);
  const [error, setError] = useState(false);
  const selectItem = useRef(
    options.find(
      (item) =>
        item.value === formData ||
        (checkPrefix(item?.value, formData) && item?.value),
    ) || options.find((item) => !item?.value || item.placeholder),
  );
  return (
    <Flex className='items-center'>
      <div
        className='fs'
        style={{ flex: layout[0] }}>
        {schema.title}
      </div>
      <Flex style={{ flex: layout[1], position: 'relative' }}>
        <AutoComplete
          style={{ width: '100%' }}
          classNames={{
            popup: {
              root: `${styles['auto-com-popup']} _self-custom-dropdown`,
            },
          }}
          disabled={disabledBoolean}
          status={error ? 'error' : ''}
          ref={AutoCompleteRef}
          options={options}
          open={open}
          placeholder={placeholder}
          value={valueInput ?? formData}
          onChange={(value: string) => {
            if (
              selectItem.current?.pattern &&
              !selectItem.current?.pattern?.test(value)
            ) {
              setError(true);
            } else {
              if (
                !selectItem.current?.isEdit &&
                value !== selectItem.current?.value
              ) {
                return;
              } else {
                onChange(value);
                setError(false);
              }
            }
            setValue(value);
          }}
          onBlur={() => {
            setOpen(false), setTimeout(() => setIsOPen(false), 100);
          }}
          onSelect={(_, d) => {
            selectItem.current = d;
            setError(d.isEdit ?? false);
            !d?.isEdit && onChange(d.value);
            setOpen(false);
            d.placeholder
              ? (setPlaceholder(d.placeholder), setValue(''))
              : (setValue(d?.title || d?.const), setPlaceholder(''));
          }}
        />
        <div
          className={styles['auto-com-icon']}
          onClick={() => {
            if (!isOPen) {
              AutoCompleteRef.current?.focus();
              setOpen(true);
              setIsOPen(true);
            }
          }}>
          <DownOutlined style={{ fontSize: 8, position: 'absolute' }} />
        </div>
      </Flex>
    </Flex>
  );
};
function checkPrefix(a: string, b: string) {
  // 将a转换为字符串并转义正则特殊字符
  const escaped = a.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  // 创建正则表达式，匹配以escapedA开头的字符串
  const regex = new RegExp(`^${escaped}.+$`);
  // 测试b是否匹配
  return regex.test(b);
}

/**
 * 
 * ui:options': {
    options: [
      {
        const: '',
        isEdit: true, // 是否可编辑
        title: 'id=', // 显示的文字
      },
      {
        const: '1', // 选中后返回的值
        title: 'create new',
      },
      { 
        //placeholder 具有唯一性  options 中只能有一个可以自由输入
        const: '',
        title: '<enter value>',
        isEdit: true, // 是否可编辑
        placeholder: '<enter value>', // 提示文字
        pattern: /^\d+$/, // 正则
      },
    ],
  },
*/
